﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WXYW.Entities;
using WXYW.DAL;
using WXYW.Model;
using System.Globalization;

namespace WXYW.BLL
{
    public class YJTJService : RepositoryBase
    {
        #region 预警统计概要信息
        public int GetWXZQAverageDays()
        {
            IQueryable<ApplicationProduct> products = GetEntities<ApplicationProduct>().Where(p => p.DistributeDateTime.HasValue && p.RepairCompleteDateTime.HasValue);
            if (products != null && products.Count() > 0)
            {
                int totalDays = 0;
                foreach (ApplicationProduct product in products)
                {
                    int daySpan = DateTimeService.CalculateDateTimeSpan(product.DistributeDateTime.Value, product.RepairCompleteDateTime.Value);
                    totalDays += daySpan;
                }

                return totalDays / products.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetBJZQAverageDays()
        {
            IQueryable<SparePartApplyForm> applications = GetEntities<SparePartApplyForm>().Where(s => s.ApplyTime.HasValue && s.SendTime.HasValue);
            if (applications != null && applications.Count() > 0)
            {
                int totalDays = 0;
                foreach (SparePartApplyForm application in applications)
                {
                    int daySpan = DateTimeService.CalculateDateTimeSpan(application.ApplyTime.Value, application.SendTime.Value);
                    totalDays += daySpan;
                }
                return totalDays / applications.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetFCZQAverageDays()
        {
            IQueryable<ReturnToFactoryForm> returnFactoryApplications = GetEntities<ReturnToFactoryForm>().Where(r => r.ApplyDate.HasValue && r.ReceiveDate.HasValue);
            if (returnFactoryApplications != null && returnFactoryApplications.Count() > 0)
            {
                int totalDays = 0;
                foreach (ReturnToFactoryForm application in returnFactoryApplications)
                {
                    int daySpan = DateTimeService.CalculateDateTimeSpan(application.ApplyDate.Value, application.ReceiveDate.Value);
                    totalDays += daySpan;
                }
                return totalDays / returnFactoryApplications.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetBAOJZQAverageDays()
        {
            IQueryable<ApplicationForm> applications = GetEntities<ApplicationForm>().Where(a => a.QuatationDatetime.HasValue && (a.Gathering != null && a.Gathering.PayDateTime.HasValue));
            if (applications != null && applications.Count() > 0)
            {
                int totalDays = 0;
                foreach (ApplicationForm application in applications)
                {
                    if (!application.GatheringReference.IsLoaded)
                    {
                        application.GatheringReference.Load();
                    }
                    int daySpan = DateTimeService.CalculateDateTimeSpan(application.QuatationDatetime.Value, application.Gathering.PayDateTime.Value);
                    totalDays += daySpan;
                }
                return totalDays / applications.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetFHZQAverageDays()
        {
            return 0;
        }

        public int GetSJZQAverageDays()
        {
            IQueryable<UpgradeForm> applications = GetEntities<UpgradeForm>(u => u.ApplyTime.HasValue && u.SendTime.HasValue);
            if (applications != null && applications.Count() > 0)
            {
                int totalDays = 0;
                foreach (UpgradeForm application in applications)
                {
                    int daySpan = DateTimeService.CalculateDateTimeSpan(application.ApplyTime.Value, application.SendTime.Value);
                    totalDays += daySpan;
                }
                return totalDays / applications.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetWXCount()
        {
            return GetEntities<ApplicationProduct>().Where(p => p.DistributeDateTime.HasValue && p.RepairCompleteDateTime.HasValue).Count();
        }

        public int GetBAOJCount()
        {
            return GetEntities<ApplicationProduct>().Where(p=>p.QuotationDateTime.HasValue && p.ConfirmQuotationDateTime.HasValue).Count();
        }

        public int GetFCCount()
        {
            return GetEntities<ReturnToFactoryForm>().Where(r => r.ApplyDate.HasValue && r.ReceiveDate.HasValue).Count();
        }

        public int GetBJCount()
        {
            return GetEntities<SparePartApplyForm>().Where(s => s.ApplyTime.HasValue && s.SendTime.HasValue).Count();
        }

        public int GetFHCount()
        {
            return 0;
        }

        public int GetSJCount()
        {
            return GetEntities<UpgradeForm>(u => u.ApplyTime.HasValue && u.SendTime.HasValue).Count();
        }
        #endregion

        #region 预警统计平台数据
        public List<YJStationModel> GetYJStationInfo()
        {
            IQueryable<ServiceStation> stations = GetEntities<ServiceStation>();
            List<YJStationModel> models = new List<YJStationModel>();
            foreach (ServiceStation station in stations)
            {
                YJStationModel model = new YJStationModel();
                model.StationName = station.Name;
                model.BAOJNotCompleteCount = GetBAOJNotCompleteCount(station.ID).ToString();
                model.BAOJZQ = GetBAOJZQAverageDays(station.ID).ToString();
                model.BJNotCompleteCount = GetBJNotCompleteCount(station.ID).ToString();
                model.BJZQ = GetBJZQAverageDays(station.ID).ToString();
                model.FCNotCompleteCount = GetFCNotCompleteCount(station.ID).ToString();
                model.FCZQ = GetFCZQAverageDays(station.ID).ToString();
                model.FHNotCompleteCount = GetFHNotCompleteCount(station.ID).ToString();
                model.FHZQ = GetFHZQAverageDays(station.ID).ToString();
                model.SJNotCompleteCount = GetSJNotCompleteCount(station.ID).ToString();
                model.SJZQ = GetSJZQAverageDays(station.ID).ToString();
                model.WXNotCompleteCount = GetWXNotCompleteCount(station.ID).ToString();
                model.WXZQ = GetWXZQAverageDays(station.ID).ToString();
                models.Add(model);
            }
            return models;
        }

        public int GetWXZQAverageDays(int stationID)
        {
            IQueryable<ApplicationProduct> products = GetEntities<ApplicationProduct>().Where(p => p.DistributeDateTime.HasValue && p.RepairCompleteDateTime.HasValue && p.ApplicationForm.ServiceStation.ID == stationID);
            if (products != null && products.Count() > 0)
            {
                int totalDays = 0;
                foreach (ApplicationProduct product in products)
                {
                    int daySpan = DateTimeService.CalculateDateTimeSpan(product.DistributeDateTime.Value, product.RepairCompleteDateTime.Value);
                    totalDays += daySpan;
                }

                return totalDays / products.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetBJZQAverageDays(int stationID)
        {
            IQueryable<SparePartApplyForm> applications = GetEntities<SparePartApplyForm>().Where(s => s.ApplyTime.HasValue && s.SendTime.HasValue && s.ServiceStation.ID == stationID);
            if (applications != null && applications.Count() > 0)
            {
                int totalDays = 0;
                foreach (SparePartApplyForm application in applications)
                {
                    int daySpan = DateTimeService.CalculateDateTimeSpan(application.ApplyTime.Value, application.SendTime.Value);
                    totalDays += daySpan;
                }
                return totalDays / applications.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetFCZQAverageDays(int stationID)
        {
            IQueryable<ReturnToFactoryForm> returnFactoryApplications = GetEntities<ReturnToFactoryForm>().Where(r => r.ApplyDate.HasValue && r.ReceiveDate.HasValue && r.ApplicationProduct.ApplicationForm.ServiceStation.ID == stationID);
            if (returnFactoryApplications != null && returnFactoryApplications.Count() > 0)
            {
                int totalDays = 0;
                foreach (ReturnToFactoryForm application in returnFactoryApplications)
                {
                    int daySpan = DateTimeService.CalculateDateTimeSpan(application.ApplyDate.Value, application.ReceiveDate.Value);
                    totalDays += daySpan;
                }
                return totalDays / returnFactoryApplications.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetBAOJZQAverageDays(int stationID)
        {
            IQueryable<ApplicationForm> applications = GetEntities<ApplicationForm>().Where(a => a.QuatationDatetime.HasValue && a.KPDateTime.HasValue && a.ServiceStation.ID == stationID);
            if (applications != null && applications.Count() > 0)
            {
                int totalDays = 0;
                foreach (ApplicationForm application in applications)
                {
                    int daySpan = DateTimeService.CalculateDateTimeSpan(application.QuatationDatetime.Value, application.KPDateTime.Value);
                    totalDays += daySpan;
                }
                return totalDays / applications.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetFHZQAverageDays(int stationID)
        {
            return 0;
        }

        public int GetSJZQAverageDays(int stationID)
        {
            IQueryable<UpgradeForm> applications = GetEntities<UpgradeForm>(u => u.ApplyTime.HasValue && u.SendTime.HasValue && u.ServiceStation.ID == stationID);
            if (applications != null && applications.Count() > 0)
            {
                int totalDays = 0;
                foreach (UpgradeForm application in applications)
                {
                    int daySpan = DateTimeService.CalculateDateTimeSpan(application.ApplyTime.Value, application.SendTime.Value);
                    totalDays += daySpan;
                }
                return totalDays / applications.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetWXNotCompleteCount(int stationID)
        {
            return GetEntities<ApplicationProduct>().Where(p => p.DistributeDateTime.HasValue && !p.RepairCompleteDateTime.HasValue && p.ApplicationForm.ServiceStation.ID == stationID).Count();
        }

        public int GetBAOJNotCompleteCount(int stationID)
        {
            return GetEntities<ApplicationForm>().Where(a => a.QuatationDatetime.HasValue && !a.KPDateTime.HasValue && a.ServiceStation.ID == stationID).Count();
        }

        public int GetFCNotCompleteCount(int stationID)
        {
            return GetEntities<ReturnToFactoryForm>().Where(r => r.ApplyDate.HasValue && !r.ReceiveDate.HasValue && r.ApplicationProduct.ApplicationForm.ServiceStation.ID == stationID).Count();
        }

        public int GetBJNotCompleteCount(int stationID)
        {
            return GetEntities<SparePartApplyForm>().Where(s => s.ApplyTime.HasValue && !s.SendTime.HasValue && s.ServiceStation.ID == stationID).Count();
        }

        public int GetFHNotCompleteCount(int stationID)
        {
            return 0;
        }

        public int GetSJNotCompleteCount(int stationID)
        {
            return GetEntities<UpgradeForm>(u => u.ApplyTime.HasValue && !u.SendTime.HasValue && u.ServiceStation.ID == stationID).Count();
        }
        #endregion

        #region 预警统计人员信息
        public List<YJPersonModel> GetYJPersonInfo()
        {
            List<YJPersonModel> models = new List<YJPersonModel>();

            IQueryable<User> users = GetEntities<User>().Where(u => u.UserType.ID != (int)RoleType.Engineer);
            foreach (User user in users)
            {
                YJPersonModel model = new YJPersonModel();
                model.PersonName = user.ContactPerson;
                model.BAOJNotCompleteCount = GetBAOJNotCompleteCount(user.UserID).ToString();
                model.BAOJZQ = GetBAOJZQAverageDays(user.UserID).ToString();
                model.BJNotCompleteCount = GetBJNotCompleteCount(user.UserID).ToString();
                model.BJZQ = GetBJZQAverageDays(user.UserID).ToString();
                model.FCNotCompleteCount = GetFCNotCompleteCount(user.UserID).ToString();
                model.FCZQ = GetFCZQAverageDays(user.UserID).ToString();
                model.FHNotCompleteCount = GetFCNotCompleteCount(user.UserID).ToString();
                model.FHZQ = GetFHZQAverageDays(user.UserID).ToString();
                model.SJNotCompleteCount = GetSJNotCompleteCount(user.UserID).ToString();
                model.SJZQ = GetSJZQAverageDays(user.UserID).ToString();
                model.WXNotCompleteCount = GetWXNotCompleteCount(user.UserID).ToString();
                model.WXZQ = GetWXZQAverageDays(user.UserID).ToString();
                models.Add(model);
            }

            return models;
        }

        public int GetWXZQAverageDays(long userID)
        {
            IQueryable<ApplicationProduct> products = GetEntities<ApplicationProduct>().Where(p => p.DistributeDateTime.HasValue && p.RepairCompleteDateTime.HasValue && p.User.UserID == userID);
            if (products != null && products.Count() > 0)
            {
                int totalDays = 0;
                foreach (ApplicationProduct product in products)
                {
                    int daySpan = DateTimeService.CalculateDateTimeSpan(product.DistributeDateTime.Value, product.RepairCompleteDateTime.Value);                    totalDays += daySpan;
                }

                return totalDays / products.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetBJZQAverageDays(long userID)
        {
            IQueryable<SparePartApplyForm> applications = GetEntities<SparePartApplyForm>().Where(s => s.ApplyTime.HasValue && s.SendTime.HasValue && s.User.UserID == userID);
            if (applications != null && applications.Count() > 0)
            {
                int totalDays = 0;
                foreach (SparePartApplyForm application in applications)
                {
                    int daySpan = DateTimeService.CalculateDateTimeSpan(application.ApplyTime.Value, application.SendTime.Value);
                    totalDays += daySpan;
                }
                return totalDays / applications.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetFCZQAverageDays(long userID)
        {
            IQueryable<ReturnToFactoryForm> returnFactoryApplications = GetEntities<ReturnToFactoryForm>().Where(r => r.ApplyDate.HasValue && r.ReceiveDate.HasValue && r.ApplicationProduct.User.UserID == userID);
            if (returnFactoryApplications != null && returnFactoryApplications.Count() > 0)
            {
                int totalDays = 0;
                foreach (ReturnToFactoryForm application in returnFactoryApplications)
                {
                    int daySpan = DateTimeService.CalculateDateTimeSpan(application.ApplyDate.Value, application.ReceiveDate.Value);
                    totalDays += daySpan;
                }
                return totalDays / returnFactoryApplications.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetBAOJZQAverageDays(long userID)
        {
            IQueryable<ApplicationForm> applications = GetEntities<ApplicationForm>().Where(a => a.QuatationDatetime.HasValue && a.User.UserID == userID);
            if (applications != null && applications.Count() > 0)
            {
                int totalDays = 0;
                foreach (ApplicationForm application in applications)
                {
                    if (application.QuatationDatetime.HasValue && application.KPDateTime.HasValue)
                    {
                        int daySpan = DateTimeService.CalculateDateTimeSpan(application.QuatationDatetime.Value, application.KPDateTime.Value);
                        totalDays += daySpan;
                    }
                }
                return totalDays / applications.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetFHZQAverageDays(long userID)
        {
            return 0;
        }

        public int GetSJZQAverageDays(long userID)
        {
            IQueryable<UpgradeForm> applications = GetEntities<UpgradeForm>(u => u.ApplyTime.HasValue && u.SendTime.HasValue && u.User.UserID == userID);
            if (applications != null && applications.Count() > 0)
            {
                int totalDays = 0;
                foreach (UpgradeForm application in applications)
                {
                    int daySpan = DateTimeService.CalculateDateTimeSpan(application.ApplyTime.Value, application.SendTime.Value);
                    totalDays += daySpan;
                }
                return totalDays / applications.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetWXNotCompleteCount(long userID)
        {
            return GetEntities<ApplicationProduct>().Where(p => p.DistributeDateTime.HasValue && !p.RepairCompleteDateTime.HasValue && p.User.UserID == userID).Count();
        }

        public int GetBAOJNotCompleteCount(long userID)
        {
            return GetEntities<ApplicationForm>().Where(a => a.QuatationDatetime.HasValue && !a.KPDateTime.HasValue && a.User.UserID == userID).Count();
        }

        public int GetFCNotCompleteCount(long userID)
        {
            return GetEntities<ReturnToFactoryForm>().Where(r => r.ApplyDate.HasValue && !r.ReceiveDate.HasValue && r.ApplicationProduct.User.UserID == userID).Count();
        }

        public int GetBJNotCompleteCount(long userID)
        {
            return GetEntities<SparePartApplyForm>().Where(s => s.ApplyTime.HasValue && !s.SendTime.HasValue && s.User.UserID == userID).Count();
        }

        public int GetFHNotCompleteCount(long userID)
        {
            return 0;
        }

        public int GetSJNotCompleteCount(long userID)
        {
            return GetEntities<UpgradeForm>(u => u.ApplyTime.HasValue && !u.SendTime.HasValue && u.User.UserID == userID).Count();
        }
        #endregion

        #region 预警统计 按维修周期
        public List<YJModelBasedOnWXZQ> GetYJTJInfoBasedOnWXZQ(int year, int month)
        {
            List<YJModelBasedOnWXZQ> models = new List<YJModelBasedOnWXZQ>();

            //IQueryable<User> users = GetEntities<User>().Where(u => u.UserType.ID != (int)RoleType.Customer && u.UserType.ID != (int)RoleType.InternalCustomer);
            IQueryable<User> users = GetEntities<User>().Where(u => u.UserType.ID == (int)RoleType.Engineer || u.UserType.ID == (int)RoleType.PlatformEngineer || u.UserType.ID == (int)RoleType.Assignee); //2013-07-20 只显示维修人员和维修派单人员
            foreach (User user in users)
            {
                YJModelBasedOnWXZQ model = new YJModelBasedOnWXZQ();
                model.PersonID = user.UserID.ToString();
                //model.PersonName = user.UserName;
                model.PersonName = user.ContactPerson;
                model.AverageDays = GetWXZQAverageDays(user.UserID, year, month).ToString();
                int reachCount = GetWXZQCompletedCount(user.UserID, year, month);
                model.CountOfReachAverage = reachCount.ToString();
                model.CountOfNotReachAverage = GetWXZQNotCompletedCount(user.UserID, year, month).ToString();
                int totalCount = GetWXZQTotalCount(user.UserID, year, month);
                if (totalCount > 0)
                {
                    model.RateOfReachAverage = (Math.Round(((double)((double)reachCount / (double)totalCount)), 2) * 100).ToString() + " %";
                }
                models.Add(model);
            }

            return models;
        }

        public int GetWXZQAverageDays(long userID, int year, int month)
        {
            IQueryable<ApplicationProduct> products = GetEntities<ApplicationProduct>().Where(p => p.DistributeDateTime.HasValue && p.RepairCompleteDateTime.HasValue 
                && (p.DistributeDateTime.Value.Year == year && p.DistributeDateTime.Value.Month == month)
                && p.User.UserID == userID);
            if (products != null && products.Count() > 0)
            {
                int totalDays = 0;
                foreach (ApplicationProduct product in products)
                {
                    int daySpan = DateTimeService.CalculateDateTimeSpan(product.DistributeDateTime.Value, product.RepairCompleteDateTime.Value);
                    totalDays += daySpan;
                }

                return totalDays / products.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetWXZQNotCompletedCount(long userID, int year, int month)
        {
            IQueryable<ApplicationProduct> products = GetEntities<ApplicationProduct>().Where(p => p.DistributeDateTime.HasValue && p.RepairCompleteDateTime.HasValue
                && (p.DistributeDateTime.Value.Year == year && p.DistributeDateTime.Value.Month == month)
                //&& (p.DistributeDateTime.Value.AddDays(2) < p.RepairCompleteDateTime.Value)
                //&& (System.Data.Linq.SqlClient.SqlMethods.DateDiffDay(p.DistributeDateTime.Value, p.RepairCompleteDateTime.Value) > 2)
                && p.User.UserID == userID);
            int count = 0;
            foreach (ApplicationProduct product in products)
            {
                if (DateTimeService.CalculateDateTimeSpan(product.DistributeDateTime.Value, product.RepairCompleteDateTime.Value) > 2)
                {
                    count++;
                }
            }
            return count;
        }

        public int GetWXZQCompletedCount(long userID, int year, int month)
        {
            IQueryable<ApplicationProduct> products = GetEntities<ApplicationProduct>().Where(p => p.DistributeDateTime.HasValue && p.RepairCompleteDateTime.HasValue
                && (p.DistributeDateTime.Value.Year == year && p.DistributeDateTime.Value.Month == month)
                //&& (p.DistributeDateTime.Value.AddDays(2) >= p.RepairCompleteDateTime.Value)
                //&& (System.Data.Linq.SqlClient.SqlMethods.DateDiffDay(p.DistributeDateTime.Value, p.RepairCompleteDateTime.Value) <= 2)
                & p.User.UserID == userID);
            int count = 0;
            foreach (ApplicationProduct product in products)
            {
                if (DateTimeService.CalculateDateTimeSpan(product.DistributeDateTime.Value, product.RepairCompleteDateTime.Value) <= 2)
                {
                    count++;
                }
            }
            return count;
        }

        public int GetWXZQTotalCount(long userID, int year, int month)
        {
            return GetEntities<ApplicationProduct>().Where(p => p.DistributeDateTime.HasValue && p.RepairCompleteDateTime.HasValue
                && (p.DistributeDateTime.Value.Year == year && p.DistributeDateTime.Value.Month == month)
                && p.User.UserID == userID).Count();
        }

        public List<YJWXZQPersonDetailModel> GetWXZQApplications(long userID, int year, int month)
        {
            List<YJWXZQPersonDetailModel> models = new List<YJWXZQPersonDetailModel>();

            IQueryable<ApplicationProduct> products = GetEntities<ApplicationProduct>().Where(p => p.DistributeDateTime.HasValue
                && (p.DistributeDateTime.Value.Year == year && p.DistributeDateTime.Value.Month == month)
                && p.User.UserID == userID);

            foreach (ApplicationProduct product in products)
            {
                YJWXZQPersonDetailModel model = new YJWXZQPersonDetailModel();
                model.BAORQ = product.QuotationDateTime.HasValue ? product.QuotationDateTime.Value.ToString("yyyy-MM-dd") : "";
                if (!product.SparePartApplyForm.IsLoaded)
                {
                    product.SparePartApplyForm.Load();
                }
                SparePartApplyForm bjForm = product.SparePartApplyForm.FirstOrDefault();
                if (bjForm != null)
                {
                    model.BJRQ = bjForm.ApplyTime.HasValue ? bjForm.ApplyTime.Value.ToString("yyyy-MM-dd") : "";
                }
                if (!product.ApplicationFormReference.IsLoaded)
                {
                    product.ApplicationFormReference.Load();
                }
                if (!product.ApplicationForm.UserReference.IsLoaded)
                {
                    product.ApplicationForm.UserReference.Load();
                }
                model.Customer = product.ApplicationForm.User.FullName;
                if (!product.ReturnToFactoryForm.IsLoaded)
                {
                    product.ReturnToFactoryForm.Load();
                }
                ReturnToFactoryForm fcForm = product.ReturnToFactoryForm.FirstOrDefault();
                if (fcForm != null)
                {
                    model.FCRQ = fcForm.ApplyDate.HasValue ? fcForm.ApplyDate.Value.ToString("yyyy-MM-dd") : "";
                }
                model.FinishRQ = product.RepairCompleteDateTime.HasValue ? product.RepairCompleteDateTime.Value.ToString("yyyy-MM-dd") : "";
                model.PDRQ = product.DistributeDateTime.HasValue ? product.DistributeDateTime.Value.ToString("yyyy-MM-dd") : "";
                model.ProblemDescription = product.ProductProblemDescription;
                //model.ProblemType = product.ProblemAnalyze.
                if (!product.ProductTypeReference.IsLoaded)
                {
                    product.ProductTypeReference.Load();
                }
                model.ProdutType = product.ProductType.ProductTypeName;
                model.RepairAccessory = product.RepairAccessory;
                model.RepairType = product.ProductRepairType;
                if (!product.UpgradeForm.IsLoaded)
                {
                    product.UpgradeForm.Load();
                }
                UpgradeForm sjForm = product.UpgradeForm.FirstOrDefault();
                if (sjForm != null)
                {                    
                    model.SJRQ = sjForm.ApplyTime.HasValue ? sjForm.ApplyTime.Value.ToString("yyyy-MM-dd") : "";
                }
                model.VersionNO = product.ProductVersionNumber;
                if (product.RepairCompleteDateTime.HasValue)
                {
                    model.WXZQ = DateTimeService.CalculateDateTimeSpan(product.DistributeDateTime.Value, product.RepairCompleteDateTime.Value).ToString();
                }
                model.RMANO = product.ApplicationForm.ApplicationCode;
                model.SerialNO = product.ProductSerialNumber;
                models.Add(model);
            }

            return models;
        }
        #endregion

        #region 按备件审批周期
        public List<YJModelBasedOnBJSQ> GetYJModelInfoBasedOnBJSQ(int year, int month)
        {
            List<YJModelBasedOnBJSQ> models = new List<YJModelBasedOnBJSQ>();
            IQueryable<ServiceStation> stations = GetEntities<ServiceStation>();

            foreach (ServiceStation station in stations)
            {
                YJModelBasedOnBJSQ model = new YJModelBasedOnBJSQ();
                model.StationID = station.ID.ToString();
                model.Station = station.Name;
                model.AverageDays = GetBJZQAverageDays(station.ID, year, month).ToString();
                int reachCount = GetBJReachAverageCount(station.ID, year, month);
                model.ReachAverageCount = reachCount.ToString();
                model.NotReachAverageCount = GetBJNotReachAverageCount(station.ID, year, month).ToString();
                int totalCount = GetBJTotalCount(station.ID, year, month);
                if (totalCount > 0)
                {
                    model.RateOfReachAverage = (Math.Round((double)((double)reachCount / (double)totalCount), 2)* 100).ToString() + " %";
                }
                models.Add(model);
            }

            return models;
        }

        public int GetBJZQAverageDays(int stationID, int year, int month)
        {
            IQueryable<SparePartApplyForm> applications = GetEntities<SparePartApplyForm>().Where(s => s.ApplyTime.HasValue && s.SendTime.HasValue && s.ServiceStation.ID == stationID &&
                s.ApplyTime.Value.Year == year && s.ApplyTime.Value.Month == month);
            if (applications != null && applications.Count() > 0)
            {
                int totalDays = 0;
                foreach (SparePartApplyForm application in applications)
                {
                    int daySpan = DateTimeService.CalculateDateTimeSpan(application.ApplyTime.Value, application.SendTime.Value);
                    totalDays += daySpan;
                }
                return totalDays / applications.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetBJReachAverageCount(int stationID, int year, int month)
        {
            IQueryable<SparePartApplyForm> applications = GetEntities<SparePartApplyForm>().Where(s => s.ApplyTime.HasValue && s.SendTime.HasValue && s.ServiceStation.ID == stationID &&
                s.ApplyTime.Value.Year == year && s.ApplyTime.Value.Month == month);
            int count = 0;
            foreach (SparePartApplyForm application in applications)
            {
                if (DateTimeService.CalculateDateTimeSpan(application.ApplyTime.Value, application.SendTime.Value) <= 2)
                {
                    count++;
                }
            }
            return count;
        }

        public int GetBJNotReachAverageCount(int stationID, int year, int month)
        {
            IQueryable<SparePartApplyForm> applications = GetEntities<SparePartApplyForm>().Where(s => s.ApplyTime.HasValue && s.SendTime.HasValue && s.ServiceStation.ID == stationID &&
               s.ApplyTime.Value.Year == year && s.ApplyTime.Value.Month == month);
            int count = 0;
            foreach (SparePartApplyForm application in applications)
            {
                if (DateTimeService.CalculateDateTimeSpan(application.ApplyTime.Value, application.SendTime.Value) > 2)
                {
                    count++;
                }
            }
            return count;
        }

        public int GetBJTotalCount(int stationID, int year, int month)
        {
            return GetEntities<SparePartApplyForm>().Where(s => s.ApplyTime.HasValue && s.SendTime.HasValue && s.ServiceStation.ID == stationID &&
               s.ApplyTime.Value.Year == year && s.ApplyTime.Value.Month == month).Count();
        }

        public List<YJModelBasedOnBJSQDetail> GetYJModelBasedOnBJSQDetailList(int stationID, int year, int month)
        {
            List<YJModelBasedOnBJSQDetail> models = new List<YJModelBasedOnBJSQDetail>();
            IQueryable<SparePartApplyForm> applications = GetEntities<SparePartApplyForm>().Where(s => s.ServiceStation.ID == stationID &&
                s.ApplyTime.HasValue && s.ApplyTime.Value.Year == year && s.ApplyTime.Value.Month == month);
            foreach (SparePartApplyForm application in applications)
            {
                YJModelBasedOnBJSQDetail model = new YJModelBasedOnBJSQDetail();
                model.FANHRQ = application.SendReturnTime.HasValue ? application.SendReturnTime.Value.ToString("yyyy-MM-dd") : "";
                model.FANHSHRQ = application.ReceiveReturnTime.HasValue ? application.ReceiveReturnTime.Value.ToString("yyyy-MM-dd") : "";
                model.FHRQ = application.SendTime.HasValue ? application.SendTime.Value.ToString("yyyy-MM-dd") : "";
                model.FHSHRQ = application.ReceiveTime.HasValue ? application.ReceiveTime.Value.ToString("yyyy-MM-dd") : "";

                if (application.ReceiveTime.HasValue && application.SendReturnTime.HasValue)
                {
                    model.FHZQ = (application.SendReturnTime.Value - application.ReceiveTime.Value).Days.ToString();
                }
                if (!application.ApplicationProductReference.IsLoaded)
                {
                    application.ApplicationProductReference.Load();
                }
                model.ProblemDescription = application.ApplicationProduct.ProductProblemDescription;
                if (!application.ApplicationProduct.ProductTypeReference.IsLoaded)
                {
                    application.ApplicationProduct.ProductTypeReference.Load();
                }
                model.ProductType = application.ApplicationProduct.ProductType.ProductTypeName;
                model.RepairType = application.ApplicationProduct.ProductRepairType;
                if (!application.ApplicationProduct.ApplicationFormReference.IsLoaded)
                {
                    application.ApplicationProduct.ApplicationFormReference.Load();
                }
                model.RMANO = application.ApplicationProduct.ApplicationForm.ApplicationCode;
                model.RunningNO = application.Code;
                model.SerialNO = application.ApplicationProduct.ProductSerialNumber;
                model.SPRQ = application.DealWithTime.HasValue ? application.DealWithTime.Value.ToString("yyyy-MM-dd") : "";
                if (application.SendTime.HasValue && application.ApplyTime.HasValue)
                {
                    model.SPZQ = DateTimeService.CalculateDateTimeSpan(application.ApplyTime.Value, application.SendTime.Value).ToString();
                }
                model.SQRQ = application.ApplyTime.HasValue ? application.ApplyTime.Value.ToString("yyyy-MM-dd") : "";
                model.VersionNO = application.ApplicationProduct.ProductVersionNumber;
                models.Add(model);
            }
            return models;
        }
        #endregion

        #region 按返厂维修周期
        public List<YJModelBasedOnFC> GetYJModelInfoBasedOnFC(int year, int month)
        {
            List<YJModelBasedOnFC> models = new List<YJModelBasedOnFC>();

            IQueryable<Provider> providers = GetEntities<Provider>();
            foreach (Provider provider in providers)
            {
                YJModelBasedOnFC model = new YJModelBasedOnFC();
                model.ProviderCode = provider.ProviderCode;
                model.AverageDays = GetFCAverageDays(provider.ProviderCode, year, month).ToString();
                int reachCount = GetFCReachAverageCount(provider.ProviderCode, year, month);
                model.ReachAverageCount = reachCount.ToString();
                model.NotReachAverageCount = GetFCNotReachAverageCount(provider.ProviderCode, year, month).ToString();
                int totalCount = GetFCTotalCount(provider.ProviderCode, year, month);
                if (totalCount > 0)
                {
                    model.RateOfReachAverage = (Math.Round(((double)(double)reachCount / (double)totalCount), 2) * 100).ToString() + " %";
                }

                models.Add(model);
            }

            return models;
        }

        public int GetFCAverageDays(string providerCode, int year, int month)
        {
            IQueryable<ReturnToFactoryForm> returnFactoryApplications = GetEntities<ReturnToFactoryForm>().Where(r => r.ApplyDate.HasValue && r.ReceiveDate.HasValue && 
                r.ApplyDate.Value.Year == year && r.ApplyDate.Value.Month == month &&
                r.ProvideCode.Equals(providerCode));
            if (returnFactoryApplications != null && returnFactoryApplications.Count() > 0)
            {
                int totalDays = 0;
                foreach (ReturnToFactoryForm application in returnFactoryApplications)
                {
                    int daySpan = DateTimeService.CalculateDateTimeSpan(application.ApplyDate.Value, application.ReceiveDate.Value);
                    totalDays += daySpan;
                }
                return totalDays / returnFactoryApplications.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetFCReachAverageCount(string providerCode, int year, int month)
        {
            IQueryable<ReturnToFactoryForm> returnFactoryApplications = GetEntities<ReturnToFactoryForm>().Where(r => r.ApplyDate.HasValue && r.ReceiveDate.HasValue &&
               r.ApplyDate.Value.Year == year && r.ApplyDate.Value.Month == month &&
               r.ProvideCode.Equals(providerCode));
            int count = 0;

            foreach (ReturnToFactoryForm application in returnFactoryApplications)
            {
                if (DateTimeService.CalculateDateTimeSpan(application.ApplyDate.Value, application.ReceiveDate.Value) <= 2)
                {
                    count++;
                }
            }

            return count;
        }

        public int GetFCNotReachAverageCount(string providerCode, int year, int month)
        {
            IQueryable<ReturnToFactoryForm> returnFactoryApplications = GetEntities<ReturnToFactoryForm>().Where(r => r.ApplyDate.HasValue && r.ReceiveDate.HasValue &&
               r.ApplyDate.Value.Year == year && r.ApplyDate.Value.Month == month &&
               r.ProvideCode.Equals(providerCode));
            int count = 0;

            foreach (ReturnToFactoryForm application in returnFactoryApplications)
            {
                if (DateTimeService.CalculateDateTimeSpan(application.ApplyDate.Value, application.ReceiveDate.Value) > 2)
                {
                    count++;
                }
            }

            return count;
        }

        public int GetFCTotalCount(string providerCode, int year, int month)
        {
            return GetEntities<ReturnToFactoryForm>().Where(r => r.ApplyDate.HasValue && r.ReceiveDate.HasValue &&
               r.ApplyDate.Value.Year == year && r.ApplyDate.Value.Month == month &&
               r.ProvideCode.Equals(providerCode)).Count();
        }

        public List<YJModelBasedOnFCDetail> GetFCDetailModelList(string providerCode, int year, int month)
        {
            List<YJModelBasedOnFCDetail> models = new List<YJModelBasedOnFCDetail>();
            IQueryable<ReturnToFactoryForm> applications = GetEntities<ReturnToFactoryForm>().Where(r => r.ApplyDate.HasValue && r.ReceiveDate.HasValue &&
               r.ApplyDate.Value.Year == year && r.ApplyDate.Value.Month == month &&
               r.ProvideCode.Equals(providerCode));

            foreach (ReturnToFactoryForm application in applications)
            {
                YJModelBasedOnFCDetail model = new YJModelBasedOnFCDetail();
                if (!application.ApplicationProductReference.IsLoaded)
                {
                    application.ApplicationProductReference.Load();
                }
                model.BJRQ = application.ApplicationProduct.QuotationDateTime.HasValue ? application.ApplicationProduct.QuotationDateTime.Value.ToString("yyyy-MM-dd") : "";
                model.ConfirmBJRQ = application.ApplicationProduct.ConfirmQuotationDateTime.HasValue ? application.ApplicationProduct.ConfirmQuotationDateTime.Value.ToString("yyyy-MM-dd") : "";
                model.FactorySHRQ = application.FactoryReceiveDate.HasValue ? application.FactoryReceiveDate.Value.ToString("yyyy-MM-dd") : "";
                model.FactoryuRMANO = application.Code;
                model.FCRQ = application.SendDate.HasValue ? application.SendDate.Value.ToString("yyyy-MM-dd") : "";
                if (application.ReceiveDate.HasValue && application.FactoryReceiveDate.HasValue)
                {
                    int timeSpan = DateTimeService.CalculateDateTimeSpan(application.FactoryReceiveDate.Value, application.ReceiveDate.Value);
                    int quoteTimeSpan = 0;
                    if (application.ApplicationProduct.QuotationDateTime.HasValue &&
                        application.ApplicationProduct.ConfirmQuotationDateTime.HasValue)
                    {
                        quoteTimeSpan = DateTimeService.CalculateDateTimeSpan(application.ApplicationProduct.QuotationDateTime.Value, application.ApplicationProduct.ConfirmQuotationDateTime.Value);
                    }
                    model.FCZQ = (timeSpan - quoteTimeSpan).ToString();
                }
                model.FinishRQ = application.ApplicationProduct.RepairCompleteDateTime.HasValue ? application.ApplicationProduct.RepairCompleteDateTime.Value.ToString("yyyy-MM-dd") : "";
                model.ProblemDescription = application.ApplicationProduct.ProductProblemDescription;
                if (!application.ApplicationProduct.ProductTypeReference.IsLoaded)
                {
                    application.ApplicationProduct.ProductTypeReference.Load();
                }
                model.ProductType = application.ApplicationProduct.ProductType.ProductTypeName;
                if (!application.ApplicationProduct.ApplicationFormReference.IsLoaded)
                {
                    application.ApplicationProduct.ApplicationFormReference.Load();
                }
                model.RMANO = application.ApplicationProduct.ApplicationForm.ApplicationCode;
                model.RunningNO = application.RunningNumber;
                model.SerialNO = application.ApplicationProduct.ProductSerialNumber;
                model.SHRQ = application.ReceiveDate.HasValue ? application.ReceiveDate.Value.ToString("yyyy-MM-dd") : "";
                model.SQRQ = application.ApplyDate.HasValue ? application.ApplyDate.Value.ToString("yyyy-MM-dd") : "";
                model.VersionNO = application.ApplicationProduct.ProductVersionNumber;
                models.Add(model);
            }

            return models;
        }
        #endregion

        #region 按报价周期
        public List<YJModelBasedOnBaoJia> GetYJModelBasedOnBaoJiaInfo(int year, int month)
        {
            List<YJModelBasedOnBaoJia> models = new List<YJModelBasedOnBaoJia>();

            IQueryable<ServiceStation> stations = GetEntities<ServiceStation>();
            foreach (ServiceStation station in stations)
            {
                YJModelBasedOnBaoJia model = new YJModelBasedOnBaoJia();
                model.StationID = station.ID.ToString();
                model.Station = station.Name;
                model.AverageDays = GetBaoJiaAverageDays(station.ID, year, month).ToString();
                model.NotReachAverageCount = GetBaoJiaNotReachAverageCount(station.ID, year, month).ToString();
                int reachCount = GetBaoJiaReachAverageCount(station.ID, year, month);
                model.ReachAverageCount = reachCount.ToString();
                int totalCount = GetBaoJiaTotalCount(station.ID, year, month);
                if (totalCount > 0)
                {
                    model.RateOfReachAverage = (Math.Round(((double)reachCount / (double)totalCount), 2) * 100).ToString() + " %";
                }
                models.Add(model);
            }

            return models;
        }

        public int GetBaoJiaAverageDays(int stationID, int year, int month)
        {
            IQueryable<ApplicationForm> applications = GetEntities<ApplicationForm>().Where(a => a.QuatationDatetime.HasValue && (a.Gathering != null && a.Gathering.PayDateTime.HasValue) &&
                a.QuatationDatetime.Value.Year == year && a.QuatationDatetime.Value.Month == month && a.ServiceStation.ID == stationID);
            if (applications != null && applications.Count() > 0)
            {
                int totalDays = 0;
                CultureInfo ciCurr = CultureInfo.CurrentCulture;
                foreach (ApplicationForm application in applications)
                {
                    if (!application.GatheringReference.IsLoaded)
                    {
                        application.GatheringReference.Load();
                    }
                    if (application.Gathering != null && application.Gathering.PayDateTime.HasValue)
                    {
                        int daySpan = DateTimeService.CalculateDateTimeSpan(new DateTime(application.QuatationDatetime.Value.Year, application.QuatationDatetime.Value.Month, application.QuatationDatetime.Value.Day),
                            application.Gathering.PayDateTime.Value);
                       
                        totalDays += daySpan;
                    }
                }
                return totalDays / applications.Count();
            }
            else
            {
                return 0;
            }
        }

        public int GetBaoJiaReachAverageCount(int stationID, int year, int month)
        {
            IQueryable<ApplicationForm> applications = GetEntities<ApplicationForm>().Where(a => a.QuatationDatetime.HasValue && (a.Gathering != null && a.Gathering.PayDateTime.HasValue) &&
                a.QuatationDatetime.Value.Year == year && a.QuatationDatetime.Value.Month == month && a.ServiceStation.ID == stationID);
            int count = 0;
            if (applications != null && applications.Count() > 0)
            {
                CultureInfo ciCurr = CultureInfo.CurrentCulture;
                foreach (ApplicationForm application in applications)
                {
                    if (!application.GatheringReference.IsLoaded)
                    {
                        application.GatheringReference.Load();
                    }
                    if (application.Gathering != null && application.Gathering.PayDateTime.HasValue)
                    {
                        int daySpan = DateTimeService.CalculateDateTimeSpan(new DateTime(application.QuatationDatetime.Value.Year, application.QuatationDatetime.Value.Month, application.QuatationDatetime.Value.Day),
                            application.Gathering.PayDateTime.Value);                       

                        if (daySpan <= 2)
                        {
                            count++;
                        }
                    }
                }
            }
            return count;
        }

        public int GetBaoJiaNotReachAverageCount(int stationID, int year, int month)
        {
            IQueryable<ApplicationForm> applications = GetEntities<ApplicationForm>().Where(a => a.QuatationDatetime.HasValue && (a.Gathering != null && a.Gathering.PayDateTime.HasValue) &&
                a.QuatationDatetime.Value.Year == year && a.QuatationDatetime.Value.Month == month && a.ServiceStation.ID == stationID);
            int count = 0;
            if (applications != null && applications.Count() > 0)
            {
                CultureInfo ciCurr = CultureInfo.CurrentCulture;
                foreach (ApplicationForm application in applications)
                {
                    if (!application.GatheringReference.IsLoaded)
                    {
                        application.GatheringReference.Load();
                    }
                    if (application.Gathering != null && application.Gathering.PayDateTime.HasValue)
                    {
                        int daySpan = DateTimeService.CalculateDateTimeSpan(new DateTime(application.QuatationDatetime.Value.Year, application.QuatationDatetime.Value.Month, application.QuatationDatetime.Value.Day),
                            application.Gathering.PayDateTime.Value);                       

                        if (daySpan > 2)
                        {
                            count++;
                        }
                    }
                }
            }
            return count;
        }

        public int GetBaoJiaTotalCount(int stationID, int year, int month)
        {
            return GetEntities<ApplicationForm>().Where(a => a.QuatationDatetime.HasValue && (a.Gathering != null && a.Gathering.PayDateTime.HasValue) &&
               a.QuatationDatetime.Value.Year == year && a.QuatationDatetime.Value.Month == month && a.ServiceStation.ID == stationID).Count();
        }

        public List<YJModelBasedOnBaoJiaDetail> GetYJModelBasedOnBaoJiaDetailList(int stationID, int year, int month)
        {
            List<YJModelBasedOnBaoJiaDetail> models = new List<YJModelBasedOnBaoJiaDetail>();

            IQueryable<ApplicationProduct> applications = GetEntities<ApplicationProduct>().Where(a => a.QuotationDateTime.HasValue && (a.ApplicationForm.Gathering != null && a.ApplicationForm.Gathering.PayDateTime.HasValue) &&
                            a.QuotationDateTime.Value.Year == year && a.QuotationDateTime.Value.Month == month && 
                            a.ApplicationForm.ServiceStation.ID == stationID);

            foreach (ApplicationProduct application in applications)
            {
                if (!application.ApplicationFormReference.IsLoaded)
                {
                    application.ApplicationFormReference.Load();
                }
                if (!application.ApplicationForm.GatheringReference.IsLoaded)
                {
                    application.ApplicationForm.GatheringReference.Load();
                }
                YJModelBasedOnBaoJiaDetail model = new YJModelBasedOnBaoJiaDetail();
                model.BJRQ = application.QuotationDateTime.HasValue ? application.QuotationDateTime.Value.ToString("yyyy-MM-dd") : "";

                int huiKuanTimeSpan = DateTimeService.CalculateDateTimeSpan(new DateTime(application.QuotationDateTime.Value.Year, application.QuotationDateTime.Value.Month, application.QuotationDateTime.Value.Day),
                    application.ApplicationForm.Gathering.PayDateTime.Value);
                
                model.HKZQ = huiKuanTimeSpan.ToString();
                model.ConfirmRQ = application.ConfirmQuotationDateTime.HasValue ? application.ConfirmQuotationDateTime.Value.ToString("yyyy-MM-dd") : "";

                int baoJiaTimeSpan = DateTimeService.CalculateDateTimeSpan(application.DistributeDateTime.Value, application.QuotationDateTime.Value);
                
                model.BJZQ = baoJiaTimeSpan.ToString();

                //model.HKZQ = application.ApplicationForm.Gathering.PayDateTime.HasValue ? application.ApplicationForm.Gathering.PayDateTime.Value.ToString("yyyy-MM-dd") : "";
                model.ProblemDescription = application.ProductProblemDescription;
                if (!application.ProductTypeReference.IsLoaded)
                {
                    application.ProductTypeReference.Load();
                }
                model.ProductType = application.ProductType.ProductTypeName;
                model.QuoteAmount = application.Cost.HasValue ? application.Cost.Value.ToString() : "";
                model.QuoteReason = application.ReasonOfCost;
                model.ReceiveMoneyRQ = application.ApplicationForm.Gathering.PayDateTime.HasValue ? application.ApplicationForm.Gathering.PayDateTime.Value.ToString("yyyy-MM-dd") : "";
                model.RepairType = application.ProductRepairType;
                model.RMANO = application.ApplicationForm.ApplicationCode;
                model.RunningNO = application.ApplicationForm.RunningNumber;
                model.RepaireAccessory = application.RepairAccessory;
                model.SerialNO = application.ProductSerialNumber;
                model.VersionNO = application.ProductVersionNumber;
                models.Add(model);
            }

            return models;
        }
        #endregion
    }
}
